import random
import string

from flask import Blueprint, render_template, request, jsonify, redirect, session, g
from sqlalchemy import desc

from app.exts import mail, database
from flask_mail import Message

from app.models import EmailCaptchaModel, Login, User, Book, Category, Borrow, Collect, Feedback

from datetime import datetime

bp = Blueprint("blueprint", __name__, url_prefix='/')


# 钩子函数
@bp.before_request
def my_before_request():
    user_id = session.get('user_id')
    user = User.query.get(user_id)
    if user:
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)


# 上下文
@bp.context_processor
def my_context_processor():
    return {"user": g.user}


# 进入项目首页
@bp.route('/')
def index():
    return render_template('index.html')


# 进入login页面
@bp.route('/loginForm')
def loginForm():
    msg = request.args.get("msg")
    if msg is None:
        msg = ""
    return render_template('login.html', msg=msg)


# 进入register页面
@bp.route('/registerForm')
def registerForm():
    msg = request.args.get("msg")
    if msg is None:
        msg = ""
    return render_template('register.html', msg=msg)


# 发送邮箱验证码进行注册
@bp.route('/<mode>/captcha')
def get_email_captcha(mode):
    email = request.args.get("email")
    # 生成验证码
    captcha = "".join(random.sample(string.digits * 4, 4))
    if mode == "register":
        message = Message(subject="您正在注册《基于Flask的智能图书管理系统》的账号！", recipients=[email],
                          body=f"您正在注册《基于Flask的智能图书管理系统》的账号！验证码是：{captcha}，请勿随意告知他人")
        mail.send(message)

        result = EmailCaptchaModel.query.filter_by(email=email).first()
        if not result:
            email = EmailCaptchaModel(email=email, captcha=captcha)
            database.session.add(email)
            database.session.commit()
        else:
            result.captcha = captcha
            database.session.commit()

        # code: 200/400/500, message:"", data:{}
        return jsonify({"code": 200, "message": "", "data": None})

    else:
        # todo：编写邮箱验证码登录
        pass


# 点击register按钮
@bp.route('/register', methods=['POST'])
def register():
    email = request.form.get("email")
    captcha = request.form.get("captcha")
    password = request.form.get("password")
    confirm_password = request.form.get("confirm-password")
    # print(email)
    # print(captcha)
    # print(password)
    # print(confirm_password)
    # 查询Login中邮箱是否重复
    data = Login.query.filter_by(email=email).first()
    if data:
        msg = "邮箱已被注册过"
        return redirect(f'/registerForm?msg={msg}')

    # 查询验证码格式
    if len(captcha) != 4:
        msg = "验证码格式错误！"
        return redirect(f'/registerForm?msg={msg}')

    # 查询邮箱和验证码是否正确
    result = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
    if result is None:
        msg = "邮箱和验证码错误！"
        return redirect(f'/registerForm?msg={msg}')

    # 查询密码格式是否正确
    if len(password) < 6:
        msg = "密码应该大于6位！"
        return redirect(f'/registerForm?msg={msg}')

    # 查询密码和确认密码是否一致
    if password != confirm_password:
        msg = "两次密码不一致！"
        return redirect(f'/registerForm?msg={msg}')

    # 删除数据库的数据
    database.session.delete(result)
    database.session.commit()

    # 在login和user表中增加对应的数据
    user_login = Login(email=email, password=password)
    user_info = User(username=email, email=email)
    database.session.add(user_login)
    database.session.add(user_info)
    database.session.commit()
    return redirect('/loginForm?msg=注册成功')


# 点击登录按钮
@bp.route('/login', methods=['POST'])
def login():
    email = request.form.get("username")
    password = request.form.get("password")
    # print(email)
    # print(password)

    data = Login.query.filter_by(email=email, password=password).first()
    if data is None:
        return redirect('/loginForm?msg=账号或密码错误')

    user = User.query.get(data.user_id)
    session['user_id'] = user.user_id
    if user.is_admin == 0:
        return redirect('/user/index')
    elif user.is_admin == 1:
        return redirect('/admin/index')


# 跳转用户主页
@bp.route('/user/index')
def user_index():
    msg = request.args.get("msg")
    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    categories = Category.query.filter().all()

    book_list = {}
    for i in range(len(categories)):
        books = Book.query.filter_by(category_id=i + 1).limit(2).all()
        if not books:
            continue
        book_list[i + 1] = books

    # print("book_list")
    # print(book_list)
    data = {
        "hot_books": hot_books,
        "categories": categories,
        "book_list": book_list,
        "msg": msg
    }

    return render_template('user/index.html', data=data)


# 跳转用户查询页面
@bp.route('/user/query')
def user_query():

    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    book_list = Book.query.filter().all()
    data = {
        "hot_books": hot_books,
        "book_list": book_list
    }
    return render_template('user/query.html', data=data)


# 搜索
@bp.route('/search')
def search():
    keyword = request.args.get('keyword')
    print(keyword)
    book_list = Book.query.filter(Book.book_name.like('%' + keyword + '%')).all()

    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    data = {
        "hot_books": hot_books,
        "book_list": book_list
    }
    return render_template('user/query.html', data=data)

# 跳转用户借阅中心
@bp.route('/user/borrow')
def user_borrow():
    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    borrows = Borrow.query.filter_by(user_id=session.get('user_id')).all()
    book_list = {}
    for borrow in borrows:
        book = Book.query.filter_by(book_id=borrow.book_id).first()
        if not book:
            continue
        book_list[borrow.borrow_id] = book
    print(borrows)
    print(book_list)

    data = {
        "hot_books": hot_books,
        "borrows": borrows,
        "book_list": book_list
    }
    return render_template('user/borrow.html', data=data)


# 点击借阅按钮
@bp.route('/borrow')
def borrow():
    book_id = request.args.get("id")
    user_id = session.get("user_id")
    print(book_id)
    print(user_id)
    borrow = Borrow.query.filter_by(user_id=user_id, book_id=book_id).first()
    if borrow is None:
        book = Book.query.get(book_id)
        book.borrow_count += 1
        book.current_number -= 1
        database.session.commit()

        borrow = Borrow(user_id=user_id, book_id=book_id)
        database.session.add(borrow)
        database.session.commit()
        print("借阅成功")

        return redirect('/user/borrow')
    else:
        pass


# 点击归还按钮
@bp.route('/return')
def return_op():
    return_id = request.args.get("id")
    borrow = Borrow.query.get(return_id)
    borrow.return_time = datetime.now()
    database.session.commit()

    book = Book.query.get(borrow.book_id)
    book.current_number += 1
    database.session.commit()

    return redirect('/user/borrow')


# 跳转用户收藏中心
@bp.route('/user/collect')
def user_collect():
    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    collects = Collect.query.filter_by(user_id=session.get('user_id')).all()
    book_list = {}
    i = 1
    for collect in collects:
        book = Book.query.filter_by(book_id=collect.book_id).first()
        book_list[i] = book
        i += 1
    print(book_list)
    data = {
        "hot_books": hot_books,
        "book_list": book_list
    }
    return render_template('user/collect.html', data=data)


# 点击收藏按钮
@bp.route('/collect')
def collect():
    msg=""
    book_id = request.args.get("id")
    user_id = session.get("user_id")
    print(book_id)
    print(user_id)

    collection = Collect.query.filter_by(user_id=user_id, book_id=book_id).first()
    if collection is None:
        collection = Collect(user_id=user_id, book_id=book_id)
        database.session.add(collection)
        database.session.commit()
        print("收藏成功")
    else:
        database.session.delete(collection)
        database.session.commit()
        print("收藏取消")
        msg = "?msg=收藏已取消"

    return redirect(f'/user/index{msg}')


# 跳转用户反馈
@bp.route('/user/feedback')
def user_feedback():
    msg = request.args.get("msg")
    if msg is None:
        msg = ""

    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    data = {
        "hot_books": hot_books,
        "msg": msg
    }
    return render_template('user/feedback.html', data=data)


# 点击用户反馈提交
@bp.route('/feedback', methods=['POST'])
def feedback():
    feedback_text = request.form.get("your_suggestion")
    print(feedback_text)
    user_id = session.get('user_id')
    print(user_id)
    feedback_obj = Feedback(user_id=user_id, message=feedback_text)
    database.session.add(feedback_obj)
    database.session.commit()

    return redirect('/user/feedback?msg=反馈成功，感谢您的建议！')


# 进入用户个人中心
@bp.route('/user/center')
def user_center():
    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    data = {
        "hot_books": hot_books
    }
    return render_template('user/center.html', data=data)


# 进入书籍详情界面
@bp.route('/user/book')
def user_book():
    hot_books = Book.query.order_by(desc(Book.borrow_count)).limit(5).all()
    # print(request.url)
    book_id = request.args.get("id")
    book = Book.query.get(book_id)

    data = {
        "hot_books": hot_books,
        "book": book
    }
    return render_template('user/book.html', data=data)


# 跳转管理员主页
@bp.route('/admin/index')
def admin_index():
    return render_template('admin/index.html')


# 退出登录
@bp.route('/exit')
def exit_action():
    session.clear()
    return redirect('/loginForm')


@bp.route('/test')
def test():
    return redirect('/user/book')
